﻿#include "canvasline.h"
#include <QGraphicsSceneMouseEvent>
#include <QStyleOptionGraphicsItem>
#include <QPainter>
#include <QDebug>

CanvasLine::CanvasLine()
{
    m_id = 0;
    m_vecPoints.clear();
}

QPainterPath CanvasLine::shape() const
{
    return m_linePath;
}

void CanvasLine::SetStart(QPointF startPos)
{
    m_vecPoints.push_back(startPos);
    m_linePath.moveTo(startPos);
}

void CanvasLine::paint(QPainter *painter,
                     const QStyleOptionGraphicsItem *option,
                     QWidget *widget)
{
    Q_UNUSED(widget);
    if (option->state & QStyle::State_Selected) {
        painter->setRenderHint(QPainter::Antialiasing, true);
        if (option->state & QStyle::State_HasFocus) {
            painter->setPen(QPen(Qt::yellow, 3));
        }
        else {
            painter->setPen(Qt::white);
        }
        painter->drawRect(boundingRect());
    }
    painter->setRenderHint(QPainter::Antialiasing, false);
    painter->drawPath(m_linePath);
}

void CanvasLine::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    QPointF pos = event->scenePos();
    if(m_vecPoints.size()==0){
        m_linePath.moveTo(pos);
    }else{
        m_linePath.lineTo(pos);
    }
    m_vecPoints.push_back(pos);
    event->accept();
    return CanvasItem::mousePressEvent(event);
    m_id = 0;
    foreach(QPointF pt,m_vecPoints){
        if(QPointF::dotProduct(pos,pt)<10){
            break;
        }
        ++m_id;
    }
    if(m_id == m_vecPoints.size()){
        //没有找到点，新增一个点
        m_vecPoints.push_back(pos);
    }
    //先画好不需要改变的线段
    setItemMode(ItemMode_Edit);
    return CanvasItem::mousePressEvent(event);
}

void CanvasLine::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    CanvasItem::mouseMoveEvent(event);
    if(m_vecPoints.size()>=2){
        update();
    }
}

void CanvasLine::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    return CanvasItem::mouseReleaseEvent(event);
}
